package com.contract.service.common;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.contract.common.error.BizException;
import com.contract.common.error.JsonReturnCode;
import com.contract.mapper.SysRegisterMapper;
import com.contract.mapper.SysUserMapper;
import com.contract.pojo.bo.SysRegister;
import com.contract.pojo.bo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Objects;

/**
 * 登录权限service
 *
 * @author liw
 * @version 1.0
 * @date 2022/9/1 17:00
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysRegisterMapper sysRegisterMapper;

    //从数据库验证用户 而不是官方的user+控制台输出的密码
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysRegister> qw = new LambdaQueryWrapper<>();
        qw.eq(SysRegister :: getOpenId, username);
        SysRegister user = sysRegisterMapper.selectOne(qw);
        if (Objects.isNull(user)) {
            throw new BizException(JsonReturnCode.USET_ERR);
        }
        return new LoginUser(user, new ArrayList<>(), new HashSet<>());
    }
}